package lee.vioson.ebook.viewmodels

import com.google.gson.Gson
import lee.vioson.composecommon.base.exception.TokenError
import lee.vioson.composecommon.base.mvi.BaseViewModel
import lee.vioson.composecommon.base.mvi.UiEvent
import lee.vioson.composecommon.base.mvi.UiState
import lee.vioson.ebook.data.AppEvent
import lee.vioson.remotedata.bean.BaseRsp
import retrofit2.HttpException
import java.net.UnknownHostException

/**
 *Author:viosonlee
 *Date:2023/6/21
 *DESCRIPTION:
 */
abstract class AppViewModel<S : UiState, E : UiEvent>(private val appEvent: AppEvent) :
    BaseViewModel<S, E>() {
    override fun handleException(e: Throwable) {
        if (e is HttpException) {
            val json = e.response()?.errorBody()?.string()
            val rsp = Gson().fromJson(json, BaseRsp::class.java)
            val msg = rsp.msg
            handleThrowable(Throwable(msg))
        } else {
            handleThrowable(e)
        }
    }

    private fun handleThrowable(e: Throwable) {
        appEvent.showLoading(false, null)
        when (e) {
            is TokenError -> {
                appEvent.reLogin()
            }

            is UnknownHostException -> {
                appEvent.showToast("网络异常")
            }

            else -> {
                appEvent.showToast(e.localizedMessage)
            }
        }
    }

    override fun showLoading(msg: String?) {
        appEvent.showLoading(true, msg)
    }

    override fun dismissLoading() {
        appEvent.showLoading(false, null)
    }

}
